import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import { useStore } from '@/hooks';
import { Checkbox, Dialog, Drawer, Message, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import CcCompanyPrice from './components/CcCompanyPrice';
import PriceForm from './components/PriceForm';
import PriceTable from './components/PriceTable';
import PriceLandTable from './components/PriceLandTable';
import PriceLandForm from './components/PriceLandForm';
import PriceTransferForm from './components/PriceTransferForm';
import PriceTransferTable from './components/PriceTransferTable';
import Orders from '@/components/Orders';

const ROUTE_TYPES = [t`内地直达`, t`跨境直达`, t`多段换乘`];
const ROUTE_ACTION = {
  1: 'editLand',
  2: 'edit',
  3: 'editTransfer',
};

function CcPrice() {
  const [args, setArgs] = useState({ priceType: 1, routeType: 2 });
  const [showOrders, setShowOrders] = useState(false);
  const { ccPriceStore: store, ccPriceTransferStore: transferStore } = useStore();
  const [modal, setModal] = useState([]);
  const [dup, setDup] = useState([]);
  const curRef = useRef(); // table中的选中行
  const [companyUpdating, setCompanyUpdating] = useState(false);

  useEffect(() => {
    if (args.routeType === 3) {
      const { routeType: _, ...restArgs } = args;
      transferStore.search = restArgs;
    } else {
      store.search = args;
    }
    (async () => {
      await store.fetchGroups();
    })();
  }, [args]);

  const handleSearch = (params) => {
    const { startArea: _, endArea: __, ...searchArgs } = params.values;
    const { startArea, endArea } = params.valueObjects;
    const arg1 = {
      startMainArea: startArea?.selectedPath?.[0]?.value,
      startMinorAreas: startArea?.selectedPath?.length > 1 ? [startArea?.selectedPath?.[1].itemId] : [],
      endMainArea: endArea?.selectedPath?.[0]?.value,
      endMinorAreas: endArea?.selectedPath?.length > 1 ? [endArea?.selectedPath?.[1].itemId] : [],
    };

    setArgs({
      ...args,
      ...arg1,
      ...searchArgs,
    });
  };

  const handleTabChange = (v) => {
    setArgs({ ...args, routeType: Number(v) + 1 });
  };

  const handleOpenCompany = (price) => {
    curRef.current = price;
    setModal(['viewCompany']);
  };

  const handleOpenOrder = (price) => {
    curRef.current = price;
    setModal(['viewOrder']);
  };

  // 点击打开添加
  const handleOpenAdd = (type) => {
    curRef.current = {};
    setModal([type]);
  };

  // 点击打开编辑
  const handleOpenEdit = (price) => {
    curRef.current = price;
    setModal([ROUTE_ACTION[args.routeType]]);
  };
  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };
  const handleTableAction = (price, action) => {
    const _store = args.routeType === 3 ? transferStore : store;
    switch (action) {
      case 'edit':
        handleOpenEdit(price);
        break;
      case 'viewCompany':
        handleOpenCompany(price);
        break;
      case 'viewOrder':
        handleOpenOrder(price);
        break;
      case 'delete':
        handleDelete(price);
        break;
      default:
        break;
    }
  };

  // 变更数据提交
  const handleUpdate = async (price) => {
    const _store = args.routeType === 3 ? transferStore : store;
    const exists = await _store.exitingLines(price);
    if (exists.length > 0 && exists[0].startMain) {
      setDup(exists);
      return;
    }

    if (!_.isEmpty(price)) {
      try {
        await _store.update(toJS(price));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (price) => {
    const _store = modal[0] === 'addTransfer' ? transferStore : store;
    const exists = await _store.exitingLines(price);
    if (exists.length > 0 && exists[0].startMain) {
      setDup(exists);
      return;
    }

    if (!_.isEmpty(price)) {
      try {
        await _store.create(toJS(price));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleDelete = (price) => {
    const _store = args.routeType === 3 ? transferStore : store;
    Dialog.confirm({
      content: t`确认删除该线路吗？`,
      onOk: async () => {
        try {
          await _store.remove(toJS(price));
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };

  const handleUpdateCompanyInfo = async () => {
    setCompanyUpdating(true);
    try {
      await store.api.updateCompanyInfo(1);
      Message.success(t`更新成功`);
    } catch (e) {
      console.error(e);
      Message.error(t`更新失败`);
    } finally {
      setCompanyUpdating(false);
      if (args.routeType === 3) {
        const { routeType: _, ...restArgs } = args;
        transferStore.search = restArgs;
      } else {
        store.search = args;
      }
      (async () => {
        await store.fetchGroups();
      })();
    }
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        className="action-panel"
        onSearch={handleSearch}
        actions={[
          {
            name: 'btn-addPrice',
            title: t`添加跨境线路`,
            type: 'primary',
            onClick: () => handleOpenAdd('add'),
          },
          {
            name: 'btn-addMainlandPrice',
            title: t`添加内地线路`,
            type: 'primary',
            onClick: () => handleOpenAdd('addLand'),
          },
          {
            name: 'btn-addTransferPrice',
            title: t`添加换乘线路`,
            type: 'primary',
            onClick: () => handleOpenAdd('addTransfer'),
          },
          {
            name: 'btn-updateCompanyInfo',
            title: t`更新承运商`,
            type: 'primary',
            onClick: handleUpdateCompanyInfo,
            loading: companyUpdating,
          },
        ]}
        searchItems={[
          {
            name: 'startArea',
            type: 'cc-station',
            props: {
              placeholder: t`始发城市/区域`,
              changeOnSelect: true,
              maxLevel: 3,
            },
          },
          {
            name: 'endArea',
            type: 'cc-station',
            props: {
              placeholder: t`到达城市/区域`,
              changeOnSelect: true,
              maxLevel: 3,
            },
          },
        ]}
      />
      <div className="content">
        <Tab
          activeKey={args.routeType - 1}
          onChange={handleTabChange}
          extra={<Checkbox onChange={(v) => setShowOrders(v)} >{t`查看订单`}</Checkbox>}
        >
          <Tab.Item key="1" title={ROUTE_TYPES[1]} />
          <Tab.Item key="0" title={ROUTE_TYPES[0]} />
          <Tab.Item key="2" title={ROUTE_TYPES[2]} />
        </Tab>
        {args.routeType === 3 && <PriceTransferTable showOrders={showOrders} onAction={handleTableAction} />}
        {args.routeType === 2 && <PriceTable showOrders={showOrders} onAction={handleTableAction} />}
        {args.routeType === 1 && <PriceLandTable showOrders={showOrders} onAction={handleTableAction} />}
      </div>
      <Drawer
        visible={modal[0] === 'viewCompany'}
        title={t`承运商价格`}
        onClose={() => setModal([])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '80%' }}
        width="90%"
      >
        <CcCompanyPrice price={curRef.current} modal={modal} onCancel={() => setModal([])} />
      </Drawer>
      <Drawer
        visible={modal[0] === 'viewOrder'}
        title={t`查看包车订单`}
        onClose={() => setModal([])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        <Orders
          orderType={1}
          hideActions
          hiddenSearchItems={['startRegion', 'endRegion', 'portType']}
          filter={_.pick(curRef.current, ['startMainArea', 'startMinorAreas', 'endMainArea', 'endMinorAreas', 'portTypes'])}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit'}
        title={modal[0] === 'add' ? t`添加跨境线路价格` : t`修改跨境线路价格 ${curRef.current?.id}`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <PriceForm
          priceId={curRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'addLand' || modal[0] === 'editLand'}
        title={modal[0] === 'addLand' ? t`添加大陆线路价格` : t`修改大陆线路价格 ${curRef.current?.id}`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <PriceLandForm
          priceId={curRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'addLand' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'addTransfer' || modal[0] === 'editTransfer'}
        title={modal[0] === 'add' ? t`添加多段线路价格` : t`修改多段线路价格 ${curRef.current?.id}`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <PriceTransferForm
          priceId={curRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'addTransfer' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Dialog
        v2
        title={t`存在重复的线路`}
        centered
        width="50%"
        height="70vh"
        onOk={() => setDup([])}
        onClose={() => setDup([])}
        visible={dup.length}
        footerActions={['ok']}
      >
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
          {/* <span>{t`重复的线路:`}</span> */}
          {dup.map((v) => <span>{`${v.startMainText}-${v.startMinorText} ---> ${v.endMainText}-${v.endMinorText}`}</span>)}
        </div>
      </Dialog>
    </TauPage>
  );
}

export default CcPrice;
